//
//  SYNavgationTitleView.swift
//  SYWeibo
//
//  Created by Saya on 16/4/6.
//  Copyright © 2016年 黄金果. All rights reserved.
//

import UIKit

class SYNavgationTitleView: UIView {
    @IBOutlet weak var tailingConstraint: NSLayoutConstraint!

    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var cancelBtn: UIButton!
    
    //提供一个类方法创建顶部view
    class func loadTitleView () -> SYNavgationTitleView{
        return NSBundle.mainBundle().loadNibNamed("SYNavgationTitleView", owner: nil, options: nil).last as! SYNavgationTitleView
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
    }
    
    //设置view的大小
    override func awakeFromNib() {
        self.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: self.bounds.height)
        //使用stretchable设置背景图片
        let searchImage :UIImage? = UIImage(named: "searchbar_textfield_background")
        searchTextField.background = searchImage?.stretchableImageWithLeftCapWidth(Int((searchImage?.size.width)!*0.5), topCapHeight: Int((searchImage?.size.height)!*0.5))
        //使用layer设置搜索边框的样式
//        searchTextField.layer.cornerRadius = 17
        searchTextField.layer.masksToBounds = true
        searchTextField.layer.borderWidth = 2
//        searchTextField.layer.borderColor = UIColor(red: 255/255.0, green: 130/255.0, blue: 0, alpha: 0.8).CGColor
        
        //设置leftView,放置放大图标
        searchTextField.leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        //设置leftView的model
        searchTextField.leftViewMode = .Always
        searchTextField.leftView?.bounds = CGRect(x: 0, y: 0, width: self.bounds.height, height: self.bounds.height)
        searchTextField.leftView?.contentMode = .Center
        
    }

    @IBAction func searchFieldDidClick(sender: AnyObject) {
        //下面一行语句执行了之后,不会立刻更改frame,一般不做任何特殊处理的时候会等该方法执行玩之后,调用layoutSubviews方法来重新绘制frame
        tailingConstraint.constant = (cancelBtn.bounds.width + 10)
        //可以在动画的闭包中手动调用layoutIfNeeded方法
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
        }
    }
    
    @IBAction func cancelBtnDidClick(sender: AnyObject) {
        tailingConstraint.constant = 0
        searchTextField.resignFirstResponder()
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
        }
    }
}
